package com.spring.cloud.config;

import com.spring.cloud.exception.ErrorApiResultHandler;
import com.spring.cloud.exception.ErrorApiResultHandlerImpl;
import com.spring.cloud.filtr.RequestProxyFilter;
import com.spring.cloud.utils.SpringContextUtil;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;


@Configuration
public class WebConfig {
    @Resource
    private ApplicationContext applicationContext;

    @PostConstruct
    public void initUtil() {
        // 初始化一系列工具类

        // 初始化SpringContextUtil
        SpringContextUtil.setApplicationContext(this.applicationContext);

    }

    /**
     * 装配一个过滤器
     * 可以将所有的request替换成RequestProxy
     *
     * @return FilterRegistrationBean
     */
    @Bean
    public FilterRegistrationBean requestProxyFilterRegistration() {

        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new RequestProxyFilter());
        registration.addUrlPatterns("/*");
        registration.setName("RequestProxyFilter");
        registration.setOrder(1);
        return registration;
    }
    @Bean
    public ErrorApiResultHandler errorApiResultHandlerImpl() {
        return new ErrorApiResultHandlerImpl();
    }

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        //自定义rest请求拦截器，可以在这里添加自定义的拦截器，拦截test请求
        //restTemplate.setInterceptors(Collections.singletonList(signClientHttpRequestInterceptor));
        return restTemplate;
    }
}

